/*
 * @author Javier A. Ramírez M.
 * jaramirez85@yahoo.es
 */

package com.jav;

import com.jav.bean.Cliente;
import com.jav.per.PersisPedido;
import com.jav.per.PersisSetup;
import com.jav.per.Persistencia;
import com.jav.util.StringUtils;
import com.sun.lwuit.Button;
import com.sun.lwuit.ComboBox;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.util.Resources;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.rms.RecordEnumeration;


public class ClienteForm  extends Form{

    private static final VentanaEspera waiting = new VentanaEspera("CARGANDO...");
    public final String PERS_PEDIDO = "PEDIDOS";
    private final String []dias = new String[]{"LU","MA","MI","JU","VI","SA"};
    private final ComboBox cbDias = new ComboBox (dias);
    private Button lb_cod = new Button(""){

        public void startTicker(long delay, boolean rightToLeft) {
            super.startTicker(200, true);
        }

    };
    private Button lb_nombre= new Button(""){

        public void startTicker(long delay, boolean rightToLeft) {
            super.startTicker(200, true);
        }

    };
    private Button lb_razon= new Button(""){

        public void startTicker(long delay, boolean rightToLeft) {
            super.startTicker(200, true);
        }

    };

    private Button lb_dir= new Button("");
    private Label lb_tel= new Label("");
    private Label estado= new Label("");
    private Vector clienteDia = new Vector();
    private int index = 0;
    private Cliente cli_select;
    private static ClienteForm _instance;
    /*private Label lb_zona_nit= new Label("");
    private Label lb_barr_ciu= new Label("");
    private Label lb_tipo_dane= new Label("");*/
    private Button lb_zona_nit= new Button("");
    private Button lb_barr_ciu= new Button("");
    private Button lb_tipo_dane= new Button("");

    /*private Label lb_zona= new Label("");
    private Label lb_nit= new Label("");
    private Label lb_barrio= new Label("");
    private Label lb_ciudad= new Label("");
    private Label lb_tipo= new Label("");
    private Label lb_dane= new Label("");*/



    public static ClienteForm getInstance(){
        if(_instance == null){
            _instance = new ClienteForm();
        }
        return _instance;
    }
    private Image imgError;

    private ClienteForm() {
        super("CLIENTES");
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        setTransitionInAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, false, 500));
        setTransitionOutAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, true, 500));

        Resources res = Datos.getInstance().getRes();
        cbDias.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                int index = cbDias.getSelectedIndex();
                carClienteDia(dias[index]);
            }
        });
        imgError = res.getImage("cancel.png");
        Container largest = createPair("Dias: ", cbDias, 30);
        int largestW = largest.getComponentAt(0).getPreferredW();
        addComponent(largest);
        addComponent(createPair("Dir: ", lb_dir, largestW));
        addComponent(createPair("Tel: ", lb_tel, largestW));
        //addComponent(createPair("Est: ", estado, largestW));
        addComponent(createPair("Cod: ", lb_cod, largestW));
        addComponent(createPair("Nom: ", lb_nombre, largestW));
        addComponent(createPair("Raz: ", lb_razon, largestW));

        /*addComponent(createQuartets("Zon:", lb_zona, "Nit: ", lb_nit));
        addComponent(createQuartets("Barrio:", lb_barrio, "Ciudad: ", lb_ciudad));
        addComponent(createQuartets("Tipo:", lb_tipo, "Dane: ",lb_dane));*/

        addComponent(lb_zona_nit);
        addComponent(lb_barr_ciu);
        addComponent(lb_tipo_dane);

        Container botonera = new Container(new BoxLayout(BoxLayout.X_AXIS));
        Button b_primero = createotonera("|<");
        b_primero.setAlignment(CENTER);
        b_primero.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                carPrimerObj();
            }
        });

        Button b_ant = createotonera("<");
        b_ant.setAlignment(CENTER);
        b_ant.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                carSigAnt(-1);
            }
        });
        Button b_sig = createotonera(">");
        b_sig.setAlignment(CENTER);
        b_sig.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                carSigAnt(1);
            }
        });
        Button b_ultimo = createotonera(">|");
        b_ultimo.setAlignment(CENTER);
        b_ultimo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                carUltimoObj();
            }
        });



        botonera.addComponent(b_primero);
        botonera.addComponent(b_ant);
        botonera.addComponent(b_sig);
        botonera.addComponent(b_ultimo);
        Container data = new Container(new BorderLayout());

        data.addComponent(BorderLayout.WEST,botonera);
        data.addComponent(BorderLayout.CENTER, estado);
        //botonera.addComponent(estado);
        addComponent(data);


        addCommand(new Command("Atrás", res.getImage("bck.png")){
             public void actionPerformed(ActionEvent evt) {
                 CapMovil.getMainForm().show();
             }
       });
       addCommand(new Command("Pedido", res.getImage("add.png")){
             public void actionPerformed(ActionEvent evt) {
                 if(cli_select != null){
                     PersisSetup pd = Datos.getInstance().getPersisSetup();
                     if (pd == null) {
                         Command okCommand = new Command("OK");
                         Dialog.show("Falló!", "Debe parametrizar el sistema primero",
                                 okCommand, new Command[]{okCommand}, Dialog.TYPE_INFO, imgError, 0, null);
                         _instance = null;
                         return;
                     }
                     boolean seguir = true;
                    try {
                        if (tienePedidos(cli_select)) {
                            seguir = Dialog.show("¿?", "EL CLIENTE YA TIENE PEDIDOS.\nDESEA CONTINUAR?", "SI", "NO");
                        }
                    } catch (Exception ex) {
                        Datos.getInstance().getLogs().append(ex.getMessage());
                    }
                     if(seguir){
                         new Thread(new Runnable() {
                             public void run() {
                                 waiting.showModeless();
                                 //Form p = new CapturaForm(cli_select);
                                 Form p = new CapturaForm(cli_select);
                                 waiting.dispose();
                                 p.show();
                            }
                        }).start();
                     }
                 }
                 else{
                     estado.setText("SELECCIONE UN CLIENTE!!");
                 }
             }
       });
       cbDias.setNextFocusUp(b_primero);
       b_primero.setNextFocusDown(cbDias);
       b_sig.setNextFocusDown(cbDias);
       b_ant.setNextFocusDown(cbDias);
       b_ultimo.setNextFocusDown(cbDias);
       carClienteDia(dias[0]);


    }

    protected Container createPair(String label, Component c, int minWidth) {
        Container pair = new Container(new BorderLayout());
        Label l =  new Label(label);
        Dimension d = l.getPreferredSize();
        d.setWidth(Math.max(d.getWidth(), minWidth));
        l.setPreferredSize(d);
        //l.getStyle().setBgTransparency(100);
        pair.addComponent(BorderLayout.WEST,l);
        pair.addComponent(BorderLayout.CENTER, c);
        return pair;
    }

   /* protected Container createQuartets(String label1, Component c1,String label2, Component c2) {
        Container pair1 = new Container(new BorderLayout());
        Container pair2 = new Container(new BorderLayout());

        //Container conte = new Container(new BoxLayout(BoxLayout.X_AXIS));
        Container conte = new Container(new BorderLayout());

        Label l =  new Label(label1);
        l.getStyle().setBgTransparency(100);
        pair1.addComponent(BorderLayout.WEST,l);
        pair1.addComponent(BorderLayout.CENTER, c1);
        Label l2 =  new Label(label2);
        l2.getStyle().setBgTransparency(100);
        pair2.addComponent(BorderLayout.WEST,l2);
        pair2.addComponent(BorderLayout.CENTER,c2);

        //conte.addComponent(pair1);
        //conte.addComponent(pair2);
        conte.addComponent(BorderLayout.WEST,pair1);
        conte.addComponent(BorderLayout.CENTER,pair2);

        return conte;
    }*/

    private void carPrimerObj() {
        Cliente cli = null;
        this.index = 0;
        if(clienteDia.size() == 0){
            return;
        }
        cli = (Cliente) clienteDia.firstElement();
        lb_cod.setText(cli.getCodigo()+ "  ord:"+cli.getOrden());
        lb_nombre.setText(cli.getNombre() + " " + cli.getApellido());
        lb_razon.setText(cli.getRazon());
        lb_dir.setText(cli.getDdrr());
        lb_tel.setText(cli.getTel());
        /*lb_zona.setText(cli.getZona());
        lb_nit.setText(cli.getNit());
        lb_barrio.setText(cli.getBarrio());
        lb_ciudad.setText(cli.getCiudad());
        lb_tipo.setText(cli.getTipo());
        lb_dane.setText(cli.getDane());*/
        lb_zona_nit.setText("ZONA: ["+cli.getZona() + "] NIT: [" + cli.getNit()+"]");
        lb_barr_ciu.setText("BARRIO: ["+cli.getBarrio() + "] CIUDAD: [" + cli.getCiudad()+"]");
        lb_tipo_dane.setText("TIPO: ["+cli.getTipo() + "] DANE:[" + cli.getDane()+"]");
        //estado.setText((this.index + 1) +"/" + clienteDia.size());
        estado.setText(StringUtils.lpad(Integer.toString(this.index + 1),'0',3) +"/" + StringUtils.lpad(Integer.toString(clienteDia.size()),'0',3));
        cli_select = cli;
    }

    private void carSigAnt(int numer){
        int sig = this.index + numer;
        if(sig < 0 || sig > (clienteDia.size()-1) ){
            return;
        }
        else{
            Cliente cli = null;
            this.index = sig;
            cli = (Cliente) clienteDia.elementAt(this.index);
            lb_cod.setText(cli.getCodigo()+ "  ord:"+cli.getOrden());
            lb_nombre.setText(cli.getNombre() + " " + cli.getApellido());
            lb_razon.setText(cli.getRazon());
            lb_dir.setText(cli.getDdrr());
            lb_tel.setText(cli.getTel());
            /*lb_zona.setText(cli.getZona());
            lb_nit.setText(cli.getNit());
            lb_barrio.setText(cli.getBarrio());
            lb_ciudad.setText(cli.getCiudad());
            lb_tipo.setText(cli.getTipo());
            lb_dane.setText(cli.getDane());*/
            lb_zona_nit.setText("ZONA: ["+cli.getZona() + "] NIT: [" + cli.getNit()+"]");
            lb_barr_ciu.setText("BARRIO: ["+cli.getBarrio() + "] CIUDAD: [" + cli.getCiudad()+"]");
            lb_tipo_dane.setText("TIPO: ["+cli.getTipo() + "] DANE:[" + cli.getDane()+"]");
            //estado.setText((this.index + 1) +"/" + clienteDia.size());
            estado.setText(StringUtils.lpad(Integer.toString(this.index + 1),'0',3) +"/" + StringUtils.lpad(Integer.toString(clienteDia.size()),'0',3));
            cli_select = cli;
        }
    }

    private void carUltimoObj() {
        Cliente cli = null;
        this.index = clienteDia.size()-1;
        if(clienteDia.size() == 0){
            return;
        }
        cli = (Cliente) clienteDia.lastElement();
        lb_cod.setText(cli.getCodigo() + "  ord:"+cli.getOrden());
        lb_nombre.setText(cli.getNombre() + " " + cli.getApellido());
        lb_razon.setText(cli.getRazon());
        lb_dir.setText(cli.getDdrr());
        lb_tel.setText(cli.getTel());
        /*lb_zona.setText(cli.getZona());
        lb_nit.setText(cli.getNit());
        lb_barrio.setText(cli.getBarrio());
        lb_ciudad.setText(cli.getCiudad());
        lb_tipo.setText(cli.getTipo());
        lb_dane.setText(cli.getDane());*/
        lb_zona_nit.setText("ZONA: ["+cli.getZona() + "] NIT: [" + cli.getNit()+"]");
        lb_barr_ciu.setText("BARRIO: ["+cli.getBarrio() + "] CIUDAD: [" + cli.getCiudad()+"]");
        lb_tipo_dane.setText("TIPO: ["+cli.getTipo() + "] DANE:[" + cli.getDane()+"]");
        estado.setText(StringUtils.lpad(Integer.toString(this.index + 1),'0',3) +"/" + StringUtils.lpad(Integer.toString(clienteDia.size()),'0',3));
        cli_select = cli;
    }
    private Button createotonera(String txt) {
        Button boton = new Button(txt);
        Dimension d = boton.getPreferredSize();
        d.setWidth(Math.max(d.getWidth(), 10));
        boton.setPreferredSize(d);
        return boton;
    }

    private void carClienteDia(String dia){
        Hashtable datos = Datos.getInstance().getClientes();
        if (datos == null){
            Command okCommand = new Command("OK");
            Dialog.show("Falló!",  "Debe cargar los datos de los Clientes",
                   okCommand,new Command[] {okCommand}, Dialog.TYPE_INFO, imgError,     0, null);
            _instance = null;
            return;
        }
        Enumeration e =datos.elements();
        clienteDia.removeAllElements();
        while (e.hasMoreElements()) {
            Cliente c = ((Cliente) e.nextElement());
            if(c.getDia().equals(dia)){
                clienteDia.addElement(c);
            }
        }
        if (clienteDia.size() > 0){
            ordenarVector();
            carPrimerObj();
        }
        else{
             lb_cod.setText("");
             lb_nombre.setText("");
             lb_razon.setText("");
             lb_dir.setText("");
             lb_tel.setText("");
             estado.setText("0/0");
             cli_select = null;

        }




    }

    private void ordenarVector() {
        Cliente []arrCli = new Cliente[clienteDia.size()];
        clienteDia.copyInto(arrCli);
        int hastai = clienteDia.size();
        int hastaj =  hastai-1;
        for (int i = 0; i < hastai; i++)
        {
            for (int j = 0; j < hastaj; j++)
            {
                int k = Integer.parseInt(arrCli[j].getOrden());
                int l = Integer.parseInt(arrCli[j+1].getOrden());
                if (k >= l)
                {
                    Cliente aux = arrCli[j];
                    arrCli[j] = arrCli[j+1];
                    arrCli[j+1] = aux;
                }
            }
        }

        clienteDia.removeAllElements();
        for (int i = 0; i < arrCli.length; i++) {
            clienteDia.addElement(arrCli[i]);
        }
    }

    public boolean tienePedidos(Cliente cliente) throws Exception {

        boolean resp = false;

        Persistencia p = null;
        try {
            p = new Persistencia(PERS_PEDIDO);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                PersisPedido pd = new PersisPedido();
                pd.resurrect(re.nextRecord());
                if(pd.getCliente().equals(cliente.getCodigo())){
                    resp = true;
                    break;
                }
            }
        } finally {
            p.close();
        }




        return resp;

    }


}
